package com.woniu.service.impl;

import com.woniu.entity.MaterialRequisition;
import com.woniu.entity.ProductInput;
import com.woniu.entity.RawMaterial;
import com.woniu.mapper.MaterialRequisitionMapper;
import com.woniu.mapper.ProductInputMapper;
import com.woniu.mapper.ProductMapper;
import com.woniu.mapper.RawMaterialMapper;
import com.woniu.service.ProductInputService;
import com.woniu.util.ResponseEnum;
import com.woniu.util.ResponseUtil;
import com.woniu.vo.ProductInputMobileVo;
import com.woniu.vo.ProductInputVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class ProductInputServiceImpl implements ProductInputService {
    @Resource
    private ProductInputMapper mapper;

    @Override
    public ResponseUtil findAll() {
        List<ProductInput> list = mapper.findAll();
        return !list.isEmpty() ? ResponseUtil.get(ResponseEnum.OK, list)
                : ResponseUtil.get(ResponseEnum.FAIL);
    }
    @Override
    public ResponseUtil findByInputId(Integer inputId) {
        ProductInput obj = mapper.findByInputId(inputId);
        return obj != null ? ResponseUtil.get(ResponseEnum.OK, obj)
                : ResponseUtil.get(ResponseEnum.FAIL);
    }
    @Override
    public ResponseUtil add(ProductInput productInput) {
        return mapper.add(productInput) > 0
                ? ResponseUtil.get(ResponseEnum.OK)
                : ResponseUtil.get(ResponseEnum.FAIL);
    }
    @Override
    public ResponseUtil delete(Integer inputId) {
        return mapper.delete(inputId) > 0
                ? ResponseUtil.get(ResponseEnum.OK)
                : ResponseUtil.get(ResponseEnum.FAIL);
    }
    @Override
    public ResponseUtil update(ProductInput productInput) {
        return mapper.update(productInput) > 0
                ? ResponseUtil.get(ResponseEnum.OK)
                : ResponseUtil.get(ResponseEnum.FAIL);
    }

    public ResponseUtil getInputForMobile(Integer inputId) {
        ProductInputMobileVo vo = productInputMapper.selectMobileVoByInputId(inputId);
        return vo != null ? ResponseUtil.get(ResponseEnum.OK,vo)
                : ResponseUtil.get(ResponseEnum.FAIL);
    }
    @Resource
    private MaterialRequisitionMapper materialRequisitionMapper;

    @Resource
    private ProductInputMapper productInputMapper;

    @Resource
    private ProductMapper productMapper;
    @Resource
    private RawMaterialMapper rawMaterialMapper;

    @Transactional  // 事务保证数据一致性
    @Override
    public ResponseUtil scanStockIn(String requisitionId) {
        // 1. 查询领料单信息
        MaterialRequisition requisition = materialRequisitionMapper.findByRequisitionId(Integer.valueOf(requisitionId));
        if (requisition == null) {
            return ResponseUtil.get(ResponseEnum.FAIL, "领料单不存在");
        }

        // 2. 验证领料单状态（例如：只有状态为2（已领取）才能入库，避免重复入库）
        if (requisition.getStatus() != 2) {
            return ResponseUtil.get(ResponseEnum.FAIL, "领料单状态异常，无法入库");
        }

        // 3. 构建成品入库记录（自动填充信息）
        ProductInput productInput = new ProductInput();
        productInput.setRequisitionId(requisitionId);
        productInput.setWarehouseId(requisition.getWarehouseId());  // 复用领料单的仓库
        productInput.setEmployeeId(requisition.getEmployeeId());    // 复用操作人
        productInput.setNum(requisition.getNum());                  // 入库数量=领料数量
        productInput.setUnitId(requisition.getUnitId());            // 复用计量单位
        productInput.setCreateTime(new Date());
        productInput.setStatus(3);  // 状态设为“已入库”（参考ProductInput的status注释）

        // 4. 查询关联的产品ID（从原材料表获取，因为领料单关联原材料，原材料关联产品）
        // 需新增RawMaterialMapper方法：通过materialId查询productId
        RawMaterial rawMaterial = rawMaterialMapper.findByMaterialId(requisition.getMaterialId());
        if (rawMaterial == null) {
            throw new RuntimeException("原材料信息不存在");
        }
        productInput.setProductId(rawMaterial.getProductId());

        // 5. 保存入库记录
        int insertResult = productInputMapper.update(productInput);
        if (insertResult <= 0) {
            throw new RuntimeException("入库记录保存失败");
        }

        // 6. 更新产品库存（增加入库数量）
        int stockResult = productMapper.increaseStock(
                Long.valueOf(rawMaterial.getProductId()),
                requisition.getNum().intValue()  // 假设num为BigDecimal，需转int
        );
        if (stockResult <= 0) {
            throw new RuntimeException("库存更新失败");
        }

        // 7. 更新领料单状态为“已入库”（例如：状态3）
        requisition.setStatus(3);
        int updateRequisition = materialRequisitionMapper.update(requisition);
        if (updateRequisition <= 0) {
            throw new RuntimeException("领料单状态更新失败");
        }

        return ResponseUtil.get(ResponseEnum.OK, "扫码入库成功");
    }

    @Override
    public ResponseUtil findAllVO() {
        List<ProductInputVO> all = mapper.findAllVO();
        return !all.isEmpty() ? ResponseUtil.get(ResponseEnum.OK, all)
                : ResponseUtil.get(ResponseEnum.FAIL);
    }
}